package dev.spb3.controller;

import dev.spb3.common.ApiResponse;
import dev.spb3.model.Book;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/books")
public class BookController {
    private List<Book> books = new ArrayList<>(
            List.of(new Book("The Great Gatsby", "Tom"),
                    new Book("Moby Dick", "Jim"),
                    new Book("War and Peace", "David")));
    @GetMapping
    public ApiResponse<List<Book>> getAllBooks() {
        return ApiResponse.success(books);
    }
    @GetMapping("/create")
    public ApiResponse<String> createBook() {
        return ApiResponse.success("创建Book");
    }
    @PostMapping("/create")
    public ApiResponse<String> createBook(@RequestBody Book book) {
        System.out.println(book);
        if (book != null) {
            books.add(new Book(book.getTitle(), book.getAuthor()));
        }
        return ApiResponse.success("创建成功");
    }
    @GetMapping("/{id}")
    public ApiResponse<Book> getBookById(@PathVariable("id") int id) {
        if (id < 0 || id >= books.size()) {
            return ApiResponse.error("Book not found", 404);
        }
        return ApiResponse.success(books.get(id));
    }
}
